import axios from 'axios';
import * as urls from './index';
import { getToken } from "./cookies";
import { message } from 'antd';

axios.defaults.timeout = 120000;
axios.defaults.baseURL = urls['baseUrl'];
axios.defaults.headers.post['Access-Control-Allow-Origin'] = '*'
axios.defaults.headers.post['Access-Control-Allow-Credentials'] = 'true'

axios.defaults.validateStatus = function (status) {
    return status >= 200 && status <= 500; // 默认的
};

axios.defaults.withCredentials = true;


axios.interceptors.request.use(config => {
    //headers中配置serialize为true开启序列化
    if (config.method === 'post' && config.headers.serialize) {
        delete config.data.serialize;
    }
    if(getToken()){
        // 判断是否有token
        config.params = {
            cookie: encodeURIComponent(getToken()), // 添加cookies参数
            ...config.params,
        }
    }
    return config
}, error => {
    return Promise.reject(error)
});


//HTTPresponse拦截
axios.interceptors.response.use(res => {
    const status = Number(res.status) || 200;
    // token过期
    if(status === 301){
        // 未登录或者是登录过期
        message.error('请先登录');
        return Promise.reject();
    }
    if(status === 403){
        // 权限不足
        return Promise.reject();
    }
    if(status === 404){
        message.error('请求资源不存在');
        return Promise.reject();
    }
    if(status === 500){
        message.error(res.msg || "服务器开小差啦");
        return Promise.reject()
    }
    return res.data;
}, error => {
    // return Promise.reject(new Error(error));
})

export default axios;
